const cloud = require('wx-server-sdk');
const axios = require('axios');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

const BANK_CODE_MAP = {
  '中国工商银行': 'ICBC',
  '工商银行': 'ICBC',
  '中国建设银行': 'CCB',
  '建设银行': 'CCB',
  '中国银行': 'BOC',
  '农业银行': 'ABC',
  '中国农业银行': 'ABC',
  '交通银行': 'BOCOM',
  '招商银行': 'CMB',
  '浦发银行': 'SPDB',
  '中信银行': 'CITIC',
  '光大银行': 'CEB',
  '华夏银行': 'HXB',
  '民生银行': 'CMBC',
  '广发银行': 'GDB',
  '平安银行': 'PAB',
  '兴业银行': 'CIB',
  '邮储银行': 'PSBC',
  '中国邮政储蓄银行': 'PSBC'
};

function parseBankCode(bankName = '') {
  if (!bankName) return 'OTHER';
  for (const [name, code] of Object.entries(BANK_CODE_MAP)) {
    if (bankName.includes(name) || name.includes(bankName)) {
      return code;
    }
  }
  return 'OTHER';
}

let cachedToken = '';
let tokenExpireAt = 0;

async function getAccessToken(apiKey, secretKey) {
  const now = Date.now();
  if (cachedToken && now < tokenExpireAt - 60 * 1000) {
    return cachedToken;
  }

  const params = new URLSearchParams({
    grant_type: 'client_credentials',
    client_id: apiKey,
    client_secret: secretKey
  });

  const response = await axios.post(
    'https://aip.baidubce.com/oauth/2.0/token',
    params.toString(),
    {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    }
  );

  if (!response.data || !response.data.access_token) {
    throw new Error('获取百度OCR token失败');
  }

  cachedToken = response.data.access_token;
  tokenExpireAt = now + (response.data.expires_in || 0) * 1000;
  return cachedToken;
}

async function downloadBase64(fileID) {
  if (!fileID || !fileID.startsWith('cloud://')) {
    throw new Error('无效的文件ID，请先上传图片到云存储');
  }

  const fileRes = await cloud.downloadFile({ fileID });
  const raw = fileRes.fileContent;

  if (!raw) {
    throw new Error('从云存储下载图片失败，请重试');
  }

  let buffer;
  if (Buffer.isBuffer(raw)) {
    buffer = raw;
  } else if (raw instanceof ArrayBuffer) {
    buffer = Buffer.from(new Uint8Array(raw));
  } else if (raw.data) {
    buffer = Buffer.from(raw.data);
  } else {
    throw new Error('图片数据格式不受支持，请重新上传');
  }

  return buffer.toString('base64');
}

exports.main = async (event) => {
  const { fileID } = event || {};
  const apiKey = process.env.BAIDU_API_KEY;
  const secretKey = process.env.BAIDU_SECRET_KEY;

  if (!apiKey || !secretKey) {
    return {
      code: 500,
      msg: '未配置百度OCR密钥，请在云函数环境变量中设置 BAIDU_API_KEY 和 BAIDU_SECRET_KEY',
      data: null
    };
  }

  try {
    const imageBase64 = await downloadBase64(fileID);
    const accessToken = await getAccessToken(apiKey, secretKey);

    const url = `https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard?access_token=${accessToken}`;
    const body = new URLSearchParams({ image: imageBase64 });
    const response = await axios.post(url, body.toString(), {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });

    if (!response.data) {
      throw new Error('百度OCR返回为空');
    }

    if (response.data.error_code) {
      const msg = `${response.data.error_code}: ${response.data.error_msg}`;
      throw new Error(msg);
    }

    const result = response.data.result || {};
    const data = {
      cardNumber: (result.bank_card_number || '').replace(/\s/g, ''),
      bankName: result.bank_name || '',
      bankCode: parseBankCode(result.bank_name || '')
    };

    return {
      code: 200,
      msg: '识别成功',
      data
    };
  } catch (error) {
    console.error('调用百度OCR失败:', error);
    return {
      code: 500,
      msg: error.message || '识别失败，请重试',
      data: null
    };
  }
};



